<script setup lang="ts">
import { ref, defineEmits, onMounted } from 'vue';
import { showToast } from 'vant';
import { addUser, getUserList as getAddedUsers } from '@/api/classroom'; // 新增 getAddedUsers 获取已添加的助教
import { getUserList } from '@/api/user';

const props = defineProps<{
  courseId: string;
  show: boolean;
}>();

const emits = defineEmits(['update:show', 'refreshAssistantList']);

const userList = ref<any[]>([]);
const assistantIds = ref<string[]>([]); // 保存已添加的助教 id
const selectedIds = ref<string[]>([]);
const isLoading = ref(false);

const onClose = () => {
  emits('update:show', false);
};

const onConfirmAdd = async () => {
  if (selectedIds.value.length === 0) {
    showToast('请选择要添加的教师');
    return;
  }
  isLoading.value = true;

  try {
    for (const id of selectedIds.value) {
      await addUser(props.courseId, id, 1); // type 1 表示助教
    }
    showToast('添加成功');
    emits('refreshAssistentList');
    onClose();
  } catch (error) {
    console.error('添加失败', error);
    showToast('添加失败');
  } finally {
    isLoading.value = false;
  }
};

onMounted(async () => {
  const userRes = await getUserList();
  if (userRes.code === 200) {
    userList.value = userRes.data || [];
  } else {
    showToast('获取用户失败');
  }

  const addedRes = await getAddedUsers(props.courseId, 1); // 获取已添加助教 type=1
  if (addedRes.code === 200) {
    assistantIds.value = (addedRes.data || []).map((u: any) => u.id);
  }
});
</script>


<template>
    <van-popup v-model:show="props.show" position="bottom" round>
      <div style="padding: 16px; position: relative">
        <van-icon
          name="cross"
          size="24"
          color="#999"
          style="position: absolute; right: 10px; top: 10px; z-index: 10"
          @click="onClose"
        />
        <div style="margin-bottom: 20px; font-weight: bold; text-align: center; font-size: 16px">
          选择要添加的教师
        </div>
  
        <van-checkbox-group v-model="selectedIds">
          <van-cell-group>
            <van-cell
              v-for="user in userList"
              :key="user.id"
              :title="user.nickname"
            >
              <template #right-icon>
                <van-checkbox
                  :name="user.id"
                  :disabled="assistantIds.includes(user.id)"
                />
              </template>
            </van-cell>
          </van-cell-group>
        </van-checkbox-group>
  
        <van-button
          type="primary"
          block
          style="margin-top: 20px"
          :loading="isLoading"
          @click="onConfirmAdd"
        >
          确认添加
        </van-button>
      </div>
    </van-popup>
  </template>
  